import React from 'react'
import {withRouter} from 'react-router'
import BaseComponent from 'basecomponent'
import classNames from 'classnames'
import icons from 'icons'
import Button from "button"
import Dropzone from 'react-dropzone'
import './style.scss'
import {Form, Select, Checkbox} from 'antd'
const FormItem = Form.Item
import api from 'apis'
const Option = Select.Option
import appConfig from 'config'
import {USER_KEY} from 'auth'
import store from 'store'
import {advType} from 'utils/staticType'

class Adv extends BaseComponent {
  constructor() {
    super(...arguments)
    const location = this.props.location
    this.state = {
      isRevise: location.state ? location.state.revise : false,
      advData: {
        Id: location.query.Id?  parseInt(location.query.Id) : -1,
        Image: '',
        Type: location.query.type?  parseInt(location.query.type) : -1,
        Name: '',
        SubName: '',
        Tag: ''
      },
      advLogoImg: '',
      advLogoPreview: '',
    }
    store.set('currentAdvId', location.query.Id ? location.query.Id : -1)
  }

  componentDidMount() {
    const {advData} = this.state
    if(this.handleID()){
      // this.getAdvDetail(advData.Id)
      if(this.props.location.state.advData){
        this.mapAdvData(this.props.location.state.advData)
        this.setState({advData: this.props.location.state.advData})
      }
    }else {
      this.mapAdvData(advData)
    }
  }

  getAdvDetail(id) {
    let advId = id ? id : store.get('currentAdvId')
    this.getAdvDetailRP && this.getAdvDetailRP.request.abort()
    this.getAdvDetailRP = api.adv.getAdvDetail(advId)
    this.registerRequest(this.getAdvDetailRP.request)
    this.getAdvDetailRP.promise
      .then((res) => {
        res.Data && this.setState({advData: res.Data})
        res.Data && this.mapAdvData(res.Data)
      })
  }

  mapAdvData(detail) {
    let tags = detail.Tag.split('  ')
    this.props.form.setFieldsValue({
      Name: detail.Name,
      Introduce: detail.Introduce,
      SubName: detail.SubName,
      tag:detail.Tag
    })
    if(detail.Image.length > 0){
      this.setState({
        advLogoPreview: `${appConfig.apiHost}/File/?pid=${detail.Image}&key=${store.get(USER_KEY)}`,
      })
    }
  }

  handleLogoFileSelect(files) {
    const {advData} = this.state
    let file = files[0]
    if (file) {
      this.uploadLogoRP && this.uploadLogoRP.request.abort()
      this.uploadLogoRP = api.file.uploadFile(file)
      this.registerRequest(this.uploadLogoRP.request)
      this.uploadLogoRP.promise
        .then((res) => {
          this.setState({
            advLogoImg: res.Data || '', advData: Object.assign({},
              advData, {Image: res.Data || ''}),
            advLogoPreview: `${appConfig.apiHost}/File/?pid=${res.Data}&key=${store.get(USER_KEY)}`
          })
        })
        .catch((err) => {
          alert(err.msg)
        })
    }
  }

  handleSubmit(e) {
    e.preventDefault()
    const{advData} = this.state
    this.props.form.validateFields((err, values) => {
      if (!err) {
        advData.Name = values.Name
        advData.SubName = values.SubName
        advData.Introduce = values.Introduce
        advData.Tag = values.tag
        if (this.handleID()){
          this.reviseAdvRP && this.reviseAdvRP.request.abort();
          this.reviseAdvRP = api.adv.reviseAdv(advData.Id, advData);
          this.registerRequest(this.reviseAdvRP.request);
          this.reviseAdvRP.promise
            .then((res) => {
              res.Data && this.setState({advData: res.Data});
              alert('修改成功')
            })
            .catch((err) => {
              alert(err.msg)
            })
        } else {
          if(!(advData.Type === -1 || typeof advData.Type === 'undefined')){
            if(advData.Id) delete advData.Id
            this.addAdvRP && this.addAdvRP.request.abort();
            this.addAdvRP = api.adv.addAdv(advData);
            this.registerRequest(this.addAdvRP.request);
            this.addAdvRP.promise
              .then((res) => {
                res.Data && this.setState({advData: res.Data});
                alert('添加成功')
              })
              .catch((err) => {
                alert(err.msg)
              })
          }
          else{
            alert('添加Adv出错')
          }
        }
      }
    })
  }
  handleID () {
    const {advData} = this.state
    return !(advData.Id === -1 || typeof advData.Id === 'undefined')
  }

  getLogoImgDiv() {
    const {advLogoImg, advLogoPreview} = this.state
    console.log('getLogoImgDiv')
    if (advLogoPreview.length > 0) {
      return <img className={'preview-img'} src={advLogoPreview}/>
    } else {
      if (advLogoImg.length > 0) {
        return <img className={'preview-img'}
                    src={`${appConfig.apiHost}/File/?pid=${advLogoImg}&key=${store.get(USER_KEY)}`}/>
      } else {
        return <div className={'default-wrapper'}>
          <img className={'image-default'} src={icons.uploadImg}/>
          <span>点击添加LOGO</span>
        </div>
      }
    }
  }

  render() {
    const {wrapperName, buttonWrapperName, clickBack, children} = this.props
    const {getFieldDecorator, getFieldsError, getFieldError, isFieldTouched} = this.props.form
    const {advData} = this.state
    const self = this
    return (
      children ? <div>{children}</div> :
        <div className={'sem-main-content'}>
          <div className={classNames('company-wrapper', wrapperName)}>
            <div className={classNames('button-wrapper', buttonWrapperName)}>
              <Button className={'back-button'} onClick={() => {
                  this.props.router.goBack()
              }}>{Button.AddOn({
                src: icons.backIcon, style: {
                  width: '1rem',
                  height: '1rem',
                  display: 'block',
                  backgroundRepeat: 'no-repeat',
                }
              })}</Button>
              <div className={'add-name'}>
                添加Adv
              </div>
            </div>
            <Form onSubmit={this.handleSubmit.bind(this)} hideRequiredMark={true}>

              <div className={'body-top'} style={{height:'auto', padding:'2rem'}}>
                <Dropzone className={'image-drop-zone'}
                          onDrop={this.handleLogoFileSelect.bind(this)}
                          accept={'image/*'}
                          multiple={false}>
                  {this.getLogoImgDiv()}
                </Dropzone>
                <div className={'body-top-middle'}>
                  <div className={'option-wrapper'}>
                    <div className={'option-title'}>名称</div>
                    <FormItem>
                      {getFieldDecorator('Name', {initialValue: advData.Name})(
                        <input className={'option-input'}
                               type={'text'}/>
                      )}
                    </FormItem>
                  </div>
                  <div className={'option-wrapper'} style={{marginBottom: '0'}}>
                    <div className={'option-title'}>副名称</div>
                    <FormItem>{
                      getFieldDecorator('SubName')(
                        <input className={'option-input'}/>
                      )
                    }</FormItem>
                  </div>
                </div>
                <div className={'body-top-end'}>
                  <div className={'option-wrapper'}>
                    <div className={'option-title'}>标签</div>
                    <FormItem>{
                      getFieldDecorator('tag')(
                        <input className={'option-input'}
                               type={'text'}/>
                      )
                    }</FormItem>
                  </div>
                </div>
              </div>

              <div className={'body-middle'}>
                <div className={'title-wrapper'}>
                  <span className={'title-bar'}/>
                  <span className={'title-text'}>Adv说明</span>
                  <Button className={'title-btn-save'} buttonType={'submit'} onClick={() => {
                  }}>保存</Button>
                </div>
                <FormItem>{
                  getFieldDecorator('Introduce', {initialValue: advData.Introduce})(
                    <textarea className={'company-intro'}/>
                  )
                }</FormItem>
              </div>
            </Form>
          </div>
        </div>
    )
  }
}

module.exports = Form.create()(withRouter(Adv))
